<template>
  <div :id="mapId" class="xm-map"></div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted, defineExpose } from 'vue';

export default defineComponent({
  emits: ['inFocus', 'submit'],
  setup(props, ctx) {
    const { id, location } = ctx.attrs
    const mapId = id || 'xmMap';
    let mapInstance = null;
    const initMap = ({center, location} = {}) => {
      // 初始化地图
      mapInstance = new AMap.Map(mapId, {
        zoom: 14, // 缩放级别
        center: center, // 设置地图中心点
        resizeEnable: true // 地图初始化加载定位到当前城市
      })

      if (location) {
        loadGeolocation(mapInstance);
      }

      ctx.emit('afterInit', mapInstance)
    }

    function loadGeolocation(map) {
      AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：5s
          position:'RB',    //定位按钮的停靠位置
          offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
        });
        map.addControl(geolocation);
      })
    }

    onMounted(() => {
      initMap({location});
    });

    return {
      mapId,
      initMap,
    };
  },
});
</script>
<style lang="less" scoped>
.xm-map {
  width: 100%;
  min-height: 300px;
}
</style>